﻿using Apex.Commons.Extentions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Apex.ASPNETCore.GlobalException
{
    public class GlobalMiddleWare
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalMiddleWare> logger;

        public GlobalMiddleWare(RequestDelegate next, ILogger<GlobalMiddleWare> logger)
        {
            _next = next;
            this.logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                //调用管道执行下一个中间件
                await _next(context);
            }
            catch (Exception ex)
            {
                if (context.Response.StatusCode == 200)
                {
                    context.Response.StatusCode = 500;
                }
                logger.LogError($"请求异常,返回信息{context.Response.Body}");
                // 设置响应的内容类型为 JSON
                context.Response.ContentType = "application/json";
                // 将报错信息转成特定格式
                string responseBodyContent = GlobalResponseResultHelper.CreateErrorResponse(context.Response.StatusCode, ex.Message).ToJsonString();
                // 将内存流的内容写回原始的 Response.Body
                await context.Response.WriteAsync(responseBodyContent);
            }
        }
    }
}